package com.cxhc.app.api;

import com.cxhc.app.api.mapper.SysUserMapStructMapper;
import com.cxhc.app.api.vo.AppUserVo;
import com.cxhc.app.api.vo.SysUserVo;
import com.cxhc.common.annotation.Anonymous;
import com.cxhc.common.constant.WechatConstants;
import com.cxhc.common.core.domain.R;
import com.cxhc.common.core.domain.entity.SysUser;
import com.cxhc.common.core.page.TableDataInfo;
import com.cxhc.common.wechat.WechatUtils;
import com.cxhc.framework.web.service.SysRegisterService;
import com.cxhc.system.domain.app.SysUserEnterprise;
import com.cxhc.system.dto.RegisteredUserDto;
import com.cxhc.system.service.app.IConfigService;
import com.cxhc.system.service.app.ISysUserEnterpriseService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.cxhc.common.core.controller.BaseController;
import com.cxhc.common.core.domain.AjaxResult;
import com.cxhc.system.service.ISysUserService;

import javax.annotation.Resource;
import java.util.List;


/**
 * 用户信息Controller
 *
 * @author Dhq
 * @date 2024-08-14
 */
@RestController
@RequestMapping("/api/SysUser")
public class ApiUser extends BaseController {
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private SysRegisterService registerService;
    @Resource
    private IConfigService configService;
    @Resource
    private ISysUserEnterpriseService enterpriseService;

    /**
     * 查询用户信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(AppUserVo vo) {
        startPage();
        SysUser sysUser = new SysUser();
        sysUser.setStatus(vo.getStatus());
        sysUser.setEntID(vo.getEntID());
        sysUser.setNickName(vo.getNickName());
        sysUser.setPhonenumber(vo.getPhone());
        sysUser.setName(vo.getName());
        if ("1".equals(vo.getIsDesensitization())){
            return getDataTable(sysUserService.selectUserListForEntDesensitization(sysUser));
        }
        return getDataTable(sysUserService.selectUserListForEnt(sysUser));
    }

    /**
     * 查询用户信息列表
     */
    @GetMapping("/listNoPage")
    public List<SysUser> listNoPage(AppUserVo vo) {
        SysUser sysUser = new SysUser();
        sysUser.setStatus(vo.getStatus());
        sysUser.setEntID(vo.getEntID());
        sysUser.setNickName(vo.getNickName());
        sysUser.setPhonenumber(vo.getPhone());
        sysUser.setName(vo.getName());
        return sysUserService.selectUserListForEnt(sysUser);
    }

    /**
     * 获取用户信息详细信息
     */
    @GetMapping(value = "/details")
    public AjaxResult getInfo(Long userId, Long entId) {
        if (ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(entId)) {
            return error("用户ID和企业ID均不可为空！！！");
        }
        return success(sysUserService.selectUserByIdForEnt(userId, entId));
    }


    /**
     * 获取用户信息详细信息
     */
    @GetMapping(value = "/info/{userId}/{endId}")
    public AjaxResult info(@PathVariable Long userId, @PathVariable Long endId) {
        return success(sysUserService.selectUserByIdForEnt(userId, endId));
    }


    /**
     * 获取用户信息详细信息
     */
    @GetMapping(value = "/info/{userId}")
    public AjaxResult info(@PathVariable Long userId) {
        return success(sysUserService.selectUserById(userId));
    }


    /**
     * 新增用户信息
     */


    @PostMapping("/insert")
    public AjaxResult add(@RequestBody SysUserVo sysUserVo) {
        SysUser sysUser = SysUserMapStructMapper.INSTANCE.SysUserVoToSysUser(sysUserVo);
        sysUser.setUserName(sysUserVo.getPhonenumber());
        Long cmAreaId = sysUserVo.getCmAreaId();
        return toAjax(sysUserService.insertUserForEnt(sysUser, cmAreaId));
    }

    /**
     * 修改用户信息
     */
    @PostMapping("/update")
    public AjaxResult edit(@RequestBody SysUserVo sysUserVo) {
        if (ObjectUtils.isEmpty(sysUserVo.getUserId()) || ObjectUtils.isEmpty(sysUserVo.getEntID())) {
            return error("用户ID和企业ID均不可为空！！！");
        }
        SysUser sysUser = SysUserMapStructMapper.INSTANCE.SysUserVoToSysUser(sysUserVo);

        return toAjax(sysUserService.updateUserForEnt(sysUser));
    }

    /**
     * 删除用户信息
     */

    @GetMapping(value = "/delete")
    public AjaxResult remove(Long userId, Long entId, Long areaId) {
        if (ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(entId) || ObjectUtils.isEmpty(areaId)) {
            return error("用户ID和企业ID和楼宇ID均不可为空！！！");
        }
        return toAjax(sysUserService.deleteForEnt(userId, entId, areaId));
    }

    /**
     * 注册用户
     *
     * @param dto
     * @return
     */
    @SneakyThrows
    @Anonymous
    @PostMapping("/registerUser")
    public R<String> registerUser(@RequestBody @Validated RegisteredUserDto dto) {
        // 获取appid
        String appid = configService.selectValueByKey(WechatConstants.APP_ID);
        // 获取secret
        String secret = configService.selectValueByKey(WechatConstants.APP_SECRET);
        // 获取token
        String token = configService.selectValueByKey(WechatConstants.APP_TOKEN);
        if (token == null) {
            return R.fail("获取token失败");
        }
        // 获取openId
        String openId = WechatUtils.getOpenId(dto.getLoginCode(), appid, secret);
        Long userId = registerService.register(dto.getPhone(), openId, 109L);
        // todo 添加到企业用户表中
        int row = enterpriseService.insertSysUserEnterprise(new SysUserEnterprise()
                .setUserID(userId)
                .setAsName(dto.getNickName())
                .setRoleID(dto.getRoleId())
                .setRoleName(dto.getRoleName())
                .setEntID(dto.getEndId())
                .setEntName(dto.getEndName())
                .setCarNo(dto.getCarNo())
                .setCarType(dto.getCarType())
                .setIdNumber(dto.getIdNumber())
                .setHomeAddress(dto.getHomeAddress())
                .setDuty(dto.getDuty())
                .setPhoto(dto.getPhoto())
                .setDescription(dto.getRemark())
                .setIsParty(dto.getIsParty().equals("是") ? "1" : "0")
        );
        return row > 0 ? R.ok("注册成功") : R.fail("注册失败");
    }

}
